package cn.itcast.handler;

import cn.itcast.message.GroupCreateRequestMessage;
import cn.itcast.message.GroupCreateResponseMessage;
import cn.itcast.server.session.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;
import java.util.Set;
@ChannelHandler.Sharable
public class GroupCreateServerMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupCreateRequestMessage msg) {
        try {
            Set<String> members = msg.getMembers();
            GroupSession groupSession = GroupSessionFactory.getGroupSession();
            Group group = groupSession.createGroup(msg.getGroupName(), members);
            GroupCreateResponseMessage responseMessage;
            if (group == null) {
                responseMessage = new GroupCreateResponseMessage(true, msg.getGroupName()+"创建聊天组成功");
                ctx.writeAndFlush(responseMessage);
                List<Channel> membersChannel = groupSession.getMembersChannel(msg.getGroupName());
                for (Channel channel : membersChannel) {
                    channel.writeAndFlush(new GroupCreateResponseMessage(true, "您已被拉入[" + msg.getGroupName()+"]"));
                }
            }else{
                ctx.writeAndFlush(new GroupCreateResponseMessage(false, "失败"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
